<?php

namespace App\Http\Controllers\Project;

use App\Models\Project\PaymentTerm;
use App\Traits\Admin\SuccessOrFailure;
use Daijulong\LaravelRoles\Permission;
use Illuminate\Http\Request;


class PaymentTermController extends  Controller
{
    use SuccessOrFailure;


    use SuccessOrFailure;

    private $permission = 'common.sign_company';


    public function index()
    {
        $this->canOrFailure($this->permission);
        $data = PaymentTerm::query()->orderBy('id')->get();

        return view('project.payment_term.index', compact('data'));
    }


    public function create()
    {
        $this->canOrFailure($this->permission);

        return view('project.payment_term.create');
    }

    public function store(Request $request)
    {
        $this->canOrFailure($this->permission);

        $attributes = $this->buildData($request);
        PaymentTerm::create($attributes);
        return $this->success('', route('admin.signCompany.index'));
    }

    public function edit($id)
    {
        $this->canOrFailure($this->permission);

        $payment_term= $this->getPaymentTermOrFail($id);
        return view('project.payment_term.edit', compact('payment_term'));
    }

    public function update(Request $request, $id)
    {
        $this->canOrFailure($this->permission);

        $sign_company = $this->getPaymentTermOrFail($id);
        $attributes = $this->buildData($request);
        $sign_company->update($attributes);

        return $this->success('', route('admin.signCompany.index'));
    }

    public function buildData($request)
    {
        $this->validate($request,
            ['name' => 'required', 'condition' => 'required', 'days' => 'required|integer'],
            ['name.required' => '请填写名称！', 'condition.required' => '请选择条件！','days.required' => '请填写天数！','days.integer' => '天数必须是数字！',]
        );

        return [
            'name' => $request->input('name'),
            'condition' => $request->input('condition'),
            'days' => $request->input('days'),
        ];
    }

    public function destroy($id)
    {
        $this->canOrFailure($this->permission);

        $sign_company = $this->getPaymentTermOrFail($id);
        $sign_company->delete();
        return $this->success();
    }

    private function getPaymentTermOrFail($id)
    {
        $data = PaymentTerm::query()->find($id);
        if (!$data) {
            response($this->failure('值不存在！'), 404)->send();
            exit;
        }
        return $data;
    }
}


